<?php 
/**create by fu */
namespace app\api\service;

use think\Request;
use think\Cache;
use app\lib\exception\TokenException;
use app\lib\exception\ForbiddenException;
use app\lib\enum\ScopeEnum;
/**
 * 
 */
class Token
{
	//生成token
	public static function generateToken()
	{
		//用三组字符串 进行MD5加密
		$one = getRandChars(32);
		$timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
		$salt = config('secure.token_salt');

		return md5($one.$timestamp.$salt);

	}

	/** 从http的header里获得key 指明需要获得的是 session_key openid uid 还是scope
	 *  
	 */
	public static function getCurrentTokenVar($key)
	{
		$token = Request::instance()->header('token');//请求头信息 token值
		$vars = Cache::get($token);                   //获取查询缓存的数据
		
		if(!$vars)throw new TokenException(['msg'=>'Token获取不到了']);

		//缓存如果是redis 获取的直接就是数组 所以加判断
		if(!is_array($vars))$vars = json_decode($vars,true);

		if(array_key_exists($key, $vars))
		{
			return $vars[$key];
		}else{
			throw new Exception('尝试获取token变量并不存在');
			
		}
	}

	//根据token 获得uid
	public static function getCurrentUid()
	{
		$uid = self::getCurrentTokenVar('uid');

		return $uid;
	} 
    // 需要用户和CMS管理员 都可以访问的权限
	public static function needPrimaryScope()
	{
		$scope = self::getCurrentTokenVar('scope');
		if(!$scope)throw new TokenException(['msg'=>'Token过期了']);

		if($scope >= ScopeEnum::User){
			return true;
		}else{
			throw new ForbiddenException();
		}
	}

	// 需要用户 可以访问的权限
	public static function needExclusiveScope()
	{
		$scope = self::getCurrentTokenVar('scope');
		if(!$scope)throw new TokenException(['msg'=>'Token过期了']);

		if($scope == ScopeEnum::User){
			return true;
		}else{
			throw new ForbiddenException();
		}
	}

	// 校验用户ID 
	public static function isValidOperate($checkedUID)
	{
		if(!$checkedUID)throw new Exception("检查UID时必须传入一个UID参数");

		$currentOperateUID = self::getCurrentUid();
		if($currentOperateUID == $checkedUID){
			return true;
		}

		return false;
	}
}




 ?>